<template>
  <div class="custom-select" @click="toggleDropdown">
    <div class="options" v-if="showDropdown">
      <div
          class="option"
          v-for="option in options"
          :key="option.value"
          @click="selectOption(option)"
      >
        {{ option.label }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
  options: {
    type: Array,
    required: true
  },
  value: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['input', 'logout', 'personal']);

const showDropdown = ref(false);
const selectedOption = ref(getSelectedOption());

function toggleDropdown() {
  showDropdown.value = !showDropdown.value;
}

function selectOption(option) {
  selectedOption.value = option;
  showDropdown.value = false;
  emit('input', option.label); // 触发更新
  // 如果选择的是退出登录选项，发出一个 logout 事件
  if (option.label === '退出登录') {
    emit('logout');
  }
  if (option.label === '个人信息') {
    emit('personal');
  }
}

function getSelectedOption() {
  return props.options.find(option => option.label === props.value) || {};
}

watch(() => props.value, (newValue) => {
  selectedOption.value = getSelectedOption();
});
</script>

<style scoped>
.custom-select {
  position: relative;
  cursor: pointer;
  padding: 10px;
  width: 100px;
  height: 5vh;
}

.options {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  color: #61716d;

  background: white;
  z-index: 10;
}

.option {
  padding: 10px;
}

.option:hover {
  background-color: #00b38a;
}
</style>
